package com.design.springboot.booksharing.component;

import com.design.springboot.booksharing.bean.ApiResult;
import com.design.springboot.booksharing.bean.Pagination;
import com.design.springboot.booksharing.enums.ApiResultCodeEnum;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * api 请求结果返回组件
 */
@SuppressWarnings({"unchecked", "rawtypes"})
@Component
public class ApiResultComponent {
    private static final Object NULL_DATA = new HashMap<>(0);

    public <T> ApiResult<T> success() {
        return success(NULL_DATA);
    }

    public <T, A> ApiResult<A> success(T object) {
        if (object instanceof Page) {
            Pagination pagination = new Pagination((Page) object);
            return (ApiResult<A>) write(ApiResultCodeEnum.SUCCESS.getCode(), ApiResultCodeEnum.SUCCESS.getMessage(), pagination);
        }
        return (ApiResult<A>) success(ApiResultCodeEnum.SUCCESS.getMessage(), object);
    }

    public <T> ApiResult<T> success(String msg, T object) {
        return write(ApiResultCodeEnum.SUCCESS.getCode(), msg, object);
    }

    public <T> ApiResult<T> error(ApiResultCodeEnum resultCodeEnum) {
        return write(resultCodeEnum.getCode(), resultCodeEnum.getMessage(), (T) NULL_DATA);
    }

    public <T> ApiResult<T> error(Integer code, String msg) {
        return write(code, msg, null);
    }

    private <T> ApiResult<T> write(Integer code, String msg, T object) {
        ApiResult<T> apiResult = new ApiResult<>();
        apiResult.setCode(code);
        apiResult.setSuccess(ApiResultCodeEnum.SUCCESS.getCode().equals(code));
        apiResult.setMsg(msg);
        apiResult.setData(object);
        return apiResult;
    }
}
